package com.lsh.service.impl;

import com.lsh.dao.*;
import com.lsh.domain.User;
import com.lsh.domain.UserDatum;
import com.lsh.domain.UserHeadPortrait;
import com.lsh.domain.UserTokens;
import com.lsh.service.LoginService;
import com.lsh.util.MD5Util;
import com.lsh.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserTokenDao userTokenDao;
    @Autowired
    private UserDatumDao userDatumDao;
    @Autowired
    private UserHeadPortraitDao userHeadPortraitDao;

    /**
     * 注册业务
     * @param user
     * @return
     */
    @Override
    public boolean regUser(User user){
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        if(username==null || password==null || email==null) return false;
        userDao.saveUser(user);
        String token = TokenUtil.buildToken(username);
        UserTokens userTokens = new UserTokens();
        userTokens.setUid(user.getId());
        userTokens.setToken(token);
        userTokens.setExpires(7200);
        userTokens.setStatus(0);
        userTokenDao.saveUserToken(userTokens);
        UserDatum userDatum = new UserDatum();
        userDatum.setUid(user.getId());
        userDatum.setNickname(user.getUsername());
        userDatumDao.saveByUserDatum(userDatum);
        userHeadPortraitDao.saveHeadPortrait(user.getId());
        return true;
    }

    /**
     * 登录业务
     * @param user
     * @return
     */
    @Override
    public String loginUser(User user) {
        String id = userDao.getByUser(user);
        if(id == null) return null;
        UserTokens userTokens = new UserTokens();
        String token = TokenUtil.buildToken(user.getUsername());
        int userId = Integer.parseInt(id);
        userTokens.setUid(userId);
        userTokens.setToken(token);
        userTokens.setStatus(1);
        int result = userTokenDao.updateUserToken(userTokens);
        if(result != 1) return null;
        return token;
    }



}
